<?php

class PagamentoBancaSella
{
	public $online;
	private $file_ric;
	private $file_ris;
	
	private $debug = true;
	private $url_test = "https://testecomm.sella.it/gestpay/pagam.asp";
	private $url_prod = "https://ecomm.sella.it/gestpay/pagam.asp";
	
	private $gestpayID;
	
	private $PAY1_UICCODE;
	private $PAY1_AMOUNT;
	private $PAY1_SHOPTRANSACTIONID;
	private $PAY1_OTP;
	
	var $db;
	

	
	function PagamentoBancaSella()
	{
		$this->online = 1;
		$this->file_ric = $_SERVER[HTTP_HOST].'/var/sellanet.ric';
		$this->file_ris = $_SERVER[HTTP_HOST].'/var/sellanet.ris';
		
	}
	
	public function gatewayURL()
	{
		$bstr = "PAY1_UICCODE=$this->PAY1_UICCODE*P1*PAY1_AMOUNT=$this->PAY1_AMOUNT*P1*PAY1_SHOPTRANSACTIONID=$this->PAY1_SHOPTRANSACTIONID*P1*PAY1_OTP=$this->PAY1_OTP";
		
		if($this->debug)$ret = $this->url_test;
		else $ret = $this->url_prod;
		$ret .= "?a=$this->gestpayID&b=$bstr";
		
		return $ret;
	}
	
	public function set_details($gestpayID="GESPAY48880", $trans_id="", $tot=0, $cur="EUR")
	{
		$this->gestpayID = $gestpayID;
		
		if($cur=="USD")$this->PAY1_UICCODE = 1;
		else $this->PAY1_UICCODE = 242;
		$this->PAY1_AMOUNT = number_format($tot,2,".","");
		$this->PAY1_SHOPTRANSACTIONID = $trans_id;
		$this->PAY1_OTP = $this->getOTP();
	}
	
	private function getOTP()
	{
		$content = file_get_contents($this->file_ric);
		$ind = strpos($content, "\n");
		$otp_ric = substr($content, 0, $ind-1);
		$new_content = substr($content,$ind+1);
		if(!file_put_contents($this->file_ric,$new_content ))exit("Error writing $this->file_ric");
		return $otp_ric;
	}
	
	private function isOTP($codice)
	{
		$content = file_get_contents($this->file_ris);
		if(strpos($content, $codice)===false) return false;
		else
		{
			$new_content = str_replace($codice."\n", "", $content);
			if(!file_put_contents($this->file_ris,$new_content ))exit("Error writing $this->file_ris");
			return true;
		}
	}
	
	public function get_esito_transazione()
	{
		$ret = array();
		$ret['querystring'] = $_SERVER['QUERY_STRING'];
		$ret['esito'] = "ERR";
		$ret[id_stato] = 6; // ERR PAGAMENTO;
		$strparams = explode("*P1*",$_REQUEST[b]);
		foreach($strparams as $param) 
		{
			$tmpparam = explode("=",$param);
			$payparams[$tmpparam[0]] = $tmpparam[1]; 
		}
		//print_r($payparams);
		if($this->isOTP($payparams[PAY1_OTP]))
		{
			$ret[esito] 	= $payparams[PAY1_TRANSACTIONRESULT];
			$ret[err_code] 	= $payparams[PAY1_ERRORCODE];
			$ret[messaggio] = $payparams[PAY1_ERRORDESCRIPTION];
			$ret[authcode] 	= $payparams[PAY1_AUTHORIZATIONCODE];
			$ret[id_transazione] = $payparams[PAY1_SHOPTRANSACTIONID];
			if($ret[esito]=="OK")$ret[id_stato] = 3; // PAGATO
			elseif($ret[esito]=="KO")$ret[id_stato] = 7; // AUTH NEGATA
		}
		//print_r($ret);
		return $ret;
	}
}